﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

using INSTA.StockApplication.DAL;
using System.Data.Entity;

namespace INSTA.StockApplication.BLL
{
    public class Employee
    {
        public Employee()
        {
            
        }

        public bool Authentification(string login, string mdp)
        {
            ApplicationStockEntities _context = new ApplicationStockEntities();

            if (_context.AGENTs.Any(o => o.PSEUDO == login && o.MDP == mdp))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public bool AddUser(UTILISATEUR user , int type)
        {
            //AJOUT DE L'UTILISATEUR
            var context = new ApplicationStockEntities();
            context.Set<UTILISATEUR>().Add(user);

            //CREATION DE L'EMPLOYEE
            var emp = new AGENT();
            emp.ID = user.ID;
            emp.ID_ROLE = type;
            emp.PSEUDO = user.NOM.ToLower();
            emp.MDP = this.generatePassword().ToLower();
            context.Set<AGENT>().Add(emp);
            return save(context);
        }

        private string generatePassword()
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var random = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 8)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());
            return result;
        }

        private bool save(ApplicationStockEntities context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var s in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entite : {0} etat {1} : ", s.Entry.Entity.GetType().Name, s.Entry.State);
                    foreach (var v in s.ValidationErrors)
                    {
                        Console.WriteLine("Propriete {0}, erreur {1} : ", v.PropertyName, v.ErrorMessage);
                    }
                }
                return false;
            }
            return true;
        }
    }
}
